package com.wocai.jrt.orgadmin.issuers.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.common.BigDecimalUtils;
import com.wocai.jrt.orgadmin.issuers.bean.IssuersResBean;
import com.wocai.jrt.orgadmin.issuers.bean.IssuersUpdateBean;
import com.wocai.jrt.orgadmin.issuers.dao.IssuersDao;
import com.wocai.jrt.orgadmin.issuers.model.Issuers;
import com.wocai.jrt.orgadmin.issuers.model.IssuersBean;
import com.wocai.jrt.orgadmin.issuers.service.spi.IssuersService;
import com.wocai.jrt.orgadmin.orders.model.Orders;
import com.wocai.jrt.orgadmin.orders.model.OrdersBean;
import com.wocai.jrt.orgadmin.orders.service.spi.OrdersService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;

/**
 * 发行方相关的service业务实现。
 * @author yinlei
 * @date 2016-3-7 15:37:31
 */
@Named
public class IssuersServiceImpl extends MyBatisServiceImpl<Issuers, IssuersBean, String> implements IssuersService {
	private static final Logger LOGGER = LoggerFactory.getLogger(IssuersServiceImpl.class);
	// 添加了方法后，记得改为private
	private IssuersDao issuersDao;
	
	@Inject
	private ProductService productServiceImpl;
	
	@Inject
	private OrdersService orderServiceImpl;
	@Override
	@Inject
	public void setBaseDao(BaseDao<Issuers, IssuersBean, String> issuersDao) {
		this.baseDao = issuersDao;
		this.issuersDao = (IssuersDao) issuersDao;
	}

	@Override
	public List<IssuersResBean> queryIssuersList(Issuers model) {
		return issuersDao.queryIssuersList(model);
	}

	@Override
	public int updateByBean(IssuersUpdateBean model) {
		return issuersDao.updateByBean(model);
	}

	@Override
	public List<Product> issuersPagedList(Product model) {
		List<Product> productLists = productServiceImpl.issuersPagedList(model);
		for (Product product : productLists) {
			List<Integer> stateList = new ArrayList<Integer>();
			stateList.add(6);
			stateList.add(7);
			stateList.add(8);
			stateList.add(3);
			OrdersBean order = new OrdersBean();
			order.createCriteria().andOrgIdEqualTo(model.getOrgId()).andStateIn(stateList).andProductIdEqualTo(product.getId());
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info("query orders list params: [{}]", JSON.toJSONString(order));
			}
			List<Orders> ordersList = orderServiceImpl.queryForList(order);
			Double raisedAmount = new Double(0L);
			for (Orders orders : ordersList) {
				Double orderAmount = new Double(0L);
				try {
					orderAmount = orders.getOrderAmount();
				} catch (NullPointerException e) {
					continue;
				} catch (Exception e) {
					continue;
				}
				raisedAmount = BigDecimalUtils.add(raisedAmount,orderAmount);
			}
			product.setAvailable(raisedAmount);
		}
		return productLists;
	}
}
